#define _SPI_HARD_GLOBAL_
#include "config.h"

uint8_t SPI_HARD_Inner_SendByte(uint8_t byte)
{
  /* Loop while DR register in not emplty */
  while (SPI_I2S_GetFlagStatus(SPI_HARD, SPI_I2S_FLAG_TXE) == RESET);

  /* Send byte through the SPI1 peripheral */
  SPI_I2S_SendData(SPI_HARD, byte);
  /* Wait to receive a byte */
  while (SPI_I2S_GetFlagStatus(SPI_HARD, SPI_I2S_FLAG_RXNE) == RESET);
  /* Return the byte read from the SPI bus */
  return SPI_I2S_ReceiveData(SPI_HARD);
}

U8 SPI_HARD_ReadByte(U8 iChipSel,U8 iRegAdd)
{
	U8 byte;
	SPI_HARD_CS_LOW();
	SPI_HARD_Inner_SendByte(iRegAdd);
	byte = SPI_HARD_Inner_SendByte(Dummy_Byte);
	SPI_HARD_CS_HIGH();
	return byte;
}

void SPI_HARD_ReadNBytes(U8 iChipSel,U8 iRegAdd,U8 *p,U16 len)
{
	U16 i;
	SPI_HARD_CS_LOW();
	SPI_HARD_Inner_SendByte(iRegAdd);
	for (i = 0;i < len;i++)
	{
		p[i] = SPI_HARD_Inner_SendByte(Dummy_Byte);
	}
	SPI_HARD_CS_HIGH();
}

void SPI_HARD_SendByte(U8 iChipSel,U8 iRegAdd,U8 iData)
{
	SPI_HARD_CS_LOW();
	SPI_HARD_Inner_SendByte(iRegAdd);
	SPI_HARD_Inner_SendByte(iData);
	SPI_HARD_CS_HIGH();
}

void SPI_HARD_SendBuffer(U8 iChipSel,U8 iRegAdd,U8* pData, U8 length)
{
	u8 i;
	SPI_HARD_CS_LOW();
	SPI_HARD_Inner_SendByte(iRegAdd);
	for(i=0;i<length;i++)
	{
		SPI_HARD_Inner_SendByte(*(pData+i));
	}
	SPI_HARD_CS_HIGH();
}


void SPI_HARD_Init(void)
{
	SPI_InitTypeDef   SPI_InitStructure;

	RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE);

	/* Configure SPI1 pins: SCK, MISO and MOSI ---------------------------------*/


	SPI_HARD_CS_INIT();
	SPI_HARD_CS_HIGH();
	GPIOA_MODE5=OUTPUT_MODE_50MHZ;GPIOA_CNF5=OUT_AL_PP;//SCK
	GPIOA_MODE6=INPUT_MODE;GPIOA_CNF6=IN_FLOATING;//MISO
	GPIOA_MODE7=OUTPUT_MODE_50MHZ;GPIOA_CNF7=OUT_AL_PP;//MOSI

	/* SPI_HARD Config -------------------------------------------------------------*/
	SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
	SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
	SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
	SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;
	SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge;
	SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
	SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_8;//SPI_BaudRatePrescaler_128;
	SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
	SPI_InitStructure.SPI_CRCPolynomial = 7;
	SPI_Init(SPI_HARD, &SPI_InitStructure);

//	SPI_SSOutputCmd(SPI_HARD,ENABLE);

	/* Enable SPI_HARD */
	SPI_Cmd(SPI_HARD, ENABLE);
}


